/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tmro.mobile.txtapark.forms;

import java.io.IOException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.Spacer;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import net.tmro.mobile.txtapark.HelloMIDlet;
import net.tmro.mobile.txtapark.MyRecordComparator;

/**
 *
 * @author tmro
 */
class HistoryForm extends Form {

    private final HelloMIDlet midlet;

    public HistoryForm(HelloMIDlet midlet) {
        super("History");
        this.midlet = midlet;
    }

    public void createUI() {
        Image image = null;
        try {
            image = Image.createImage("txt-a-park.png");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        this.append(new ImageItem("", image, ImageItem.LAYOUT_NEWLINE_AFTER, "TXT-a-Park"));
        
        try {
            // load the history from the RMS
            RecordStore recordStore = RecordStore.openRecordStore("txtapark", true);

            RecordEnumeration re = recordStore.enumerateRecords(null, new MyRecordComparator(), false);

            if(re.numRecords() == 0){
                this.append("Once you start using the application you will see here a list of all the txt messages that you had sent. They will have a timestamp and your notes so that you can recall why when or where you parked");
            }

            while (re.hasNextElement()) {
                byte nextRec[] = re.nextRecord();
                String entry = new String(nextRec);
                System.out.println("Loaded entry=" + entry);
                if (entry.equals(HelloMIDlet.HISTORY_SEPARATOR)) {
                    this.append(new Spacer(10, 5));
                } else {
                    this.append(entry);
                }
            }

            recordStore.closeRecordStore();

        } catch (RecordStoreException ex) {
            final Alert alert = new Alert("Error");
            alert.setString("An error occurred while reading your history. " + ex.getMessage());
            Display.getDisplay(midlet).setCurrent(alert, this);

            ex.printStackTrace();
        }
    }
}
